<?php
/**
 *
 * @author Strawberry🍓
 * @date 2021-05-21 4:08 下午
 *
 */

namespace app\common\model\tang;
//ini_set('display_errors', 'on');

use app\admin\controller\WatchMaintainList;
use app\common\impl\Comm;
use app\common\model\CommonBaseModel;
use app\common\model\tang\MerchantMobile;
use think\facade\Db;
use think\facade\Session;

class Merchant extends CommonBaseModel implements Comm
{


    public function getAdminPageData($param = [], $order = 'id desc')
    {
        // TODO: Implement getAdminPageData() method.
        $where = [];

        $model = self::where($where);

        if (isset($param['merchant_sn']) && $param['merchant_sn']) {
            $model->where('merchant_sn', 'like', "%{$param['merchant_sn']}%");
        }
        if (isset($param['activities']) && $param['activities']) {
            $model->where('activities', 'like', "%{$param['activities']}%");
        }
        if (isset($param['name']) && $param['name']) {
            $model->where('name', 'like', "%{$param['name']}%");
        }
        if (isset($param['lcName']) && $param['lcName']) {
            $model->where('lcName', '=', $param['lcName']);
        }
        if (isset($param['company']) && $param['company']) {
            $model->where('company', 'like', "%{$param['company']}%");
        }
        if (isset($param['type']) && $param['type']) {
            $model->where('type', '=', $param['type']);
        }
        if (isset($param['biz_state']) && $param['biz_state']) {
            $model->where('biz_state', '=', $param['biz_state']);
        }
        if (isset($param['contract_type']) && $param['contract_type']) {
            $model->where('contract_type', '=', $param['contract_type']);
        }
        if (isset($param['positionType']) && $param['positionType']) {
            $model->where('positionType', '=', $param['positionType']);
        }
        if (isset($param['code']) && $param['code']) {
            $model->where('code', '=', $param['code']);
        }
        if (isset($param['mobile']) && $param['mobile']) {
            $model->where('mobile', 'like', "%{$param['mobile']}%");
        }

        $count = $model->count("id");

        $data = $model->with(['organization','organizationOne'])->order($order)->page(PAGE)->limit(LIMIT)->select(); // ->toArray()
        $newdata = [] ;
        if(!empty($data)){
            error_reporting(E_ALL ^ E_NOTICE);
            foreach ($data as $row){
                $newdata[] = $row ;
            }
        }

        return parent::ajaxResult($newdata, $count);
    }

    public function AddMerchant($username, $mobile)
    {
        Db::startTrans();
        try {
            $Merchant = self::where('mobile', $mobile)->find();
            if ($Merchant) {
                if ($Merchant['username'] != $username) {
                    $result = self::update([
                        'username' => $username
                    ], ['id' => $Merchant['id']]);

                }
                $merchant_id = $Merchant['id'];
            } else {
                $MerchantSn = MerchantSn();
                $data = [
                    'merchant_sn' => $MerchantSn,
                    'username' => $username,
                    'mobile' => $mobile,
                    'type' => 2,
                    'create_time' => time(),
                    'update_time' => time(),
                ];
                $merchant = new Merchant();
                $merchant->save($data);
                $merchant_id = $merchant->id;

                $MerchantMobile = new MerchantMobile();
                $is_mobile = $MerchantMobile->where('mobile', $mobile)->find();
                if ($is_mobile) {
                    return false;
                }
                $list = [
                    'mobile' => $mobile,
                    'merchant_id' => $merchant_id,
                    'createtime' => time(),
                ];
                $addmobile = $MerchantMobile->save($list);
            }
            Db::commit();
            return $merchant_id;
        } catch (\Exception $exception) {
            Db::rollback();
            return false;
        }
    }

    public function delById($id)
    {
        // TODO: Implement delById() method.
        $result = self::update([
            'status' => -1
        ], ['id' => $id]);
        if ($result) {
            return self::JsonReturn("冻结成功");
        } else {
            return self::JsonReturn("冻结失败", 0);
        }
    }

    public function doAll($data)
    {
        Db::startTrans();
        try {
            $MerchantMobile = new MerchantMobile();
            $allMobile = explode(',', $data['mobile']);
            if (empty($allMobile)) {
                return self::JsonReturn("手机号不能为空", 0);
            }
//            else {
//                foreach ($allMobile as $v) {
//                    $mobile = $MerchantMobile->where('mobile', $v)->find();
//                    if ($mobile) {
//                        if (empty($data['id'])) {
//                            return self::JsonReturn("手机号" . $v . '已经被注册,请重新填写', 0);
//                        } else {
//                            if ($mobile['merchant_id'] != $data['id']) {
//                                return self::JsonReturn("手机号" . $v . '已经被注册,请重新填写', 0);
//                            }
//                        }
//                    }
//                }
//            }

            if (!empty($data['id'])) {
                $all = $MerchantMobile->where('merchant_id', $data['id'])->select()->toArray();
                if (!empty($all)) {
                    $result = $MerchantMobile->where('merchant_id', $data['id'])->delete();
                    if (!$result) {
                        return self::JsonReturn("修改失败", 0);
                    }
                }
                if(isset($data['select'])){
                    $data['task_id'] = $data['select'];
                    unset($data['select']);
                }
                $Merchan = self::update($data, ['id' => $data['id']]);
                if (!$Merchan) {
                    return self::JsonReturn("更新失败", 0);
                }
            } else {
                unset($data['__token__']);
                $Merchan = new Merchant();
                if(isset($data['select'])){
                    $data['task_id'] = $data['select'];
                    unset($data['select']);
                }
                $data['create_time'] = time();
                $data['biz_state'] = 'effect';
                $data['password'] = md5(123456);
                $data['code'] = OrderSn();
                $WatchMaintainList =new WatchMaintain();
//                $result = $Merchan->where('merchant_sn',$data['merchant_sn'])->find();
//                if(empty($result)){
//                    return self::JsonReturn("请输入正确的商户编号",0);
//                }
//                if($result['status']!=-1){
//                    return self::JsonReturn("请先将用户数据冻结",0);
//                }

                $merchantId =$Merchan->insertGetId($data);//新增时获取ID
                //找出原商户的水电表
//                $watchInfo = $WatchMaintainList->where('merchant_id',$result['id'])->select();
//                if(empty($watchInfo)){
//                    return self::JsonReturn("该商户暂无水电表",0);
//                }
//                $WatchMaintainList->where('merchant_id',$result['id'])->update([
//                    'merchant_id'=>$merchantId
//                ]);
            }

            if (!empty($allMobile)) {
                $list = [];
                foreach ($allMobile as $k => $v) {
                    if (!empty($v)) {
                        $list[$k]['mobile'] = $v;
                        $list[$k]['merchant_id'] = $Merchan->id?$Merchan->id :$merchantId;
                        $list[$k]['createtime'] = time();
                    }
                }
                $addmobile = $MerchantMobile->saveAll($list);
                if (!$addmobile) {
                    return self::JsonReturn("更新失败", 0);
                }
            }
            // 提交事务
            Db::commit();
            return self::JsonReturn("更新添加成功");
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return self::JsonReturn($e->getMessage(), 0);
        }


    }
    //
    public function getExportPageData($param,$where=[]){

        $model = self::where($where);
        if (isset($param['activities']) && $param['activities']) {
            $model->where('activities', 'like', "%{$param['activities']}%");
        }
        if (isset($param['biz_state']) && $param['biz_state']) {
            $model->where('biz_state', '=', $param['biz_state']);
        }
        if (isset($param['contract_type']) && $param['contract_type']) {
            $model->where('contract_type', '=', $param['contract_type']);
        }
        if (isset($param['positionType']) && $param['positionType']) {
            $model->where('positionType', '=', $param['positionType']);
        }
        if (isset($param['lcName']) && $param['lcName']) {
            $model->where('lcName', '=', $param['lcName']);
        }


        $data = $model->with(['merchantInvoice'])->select()->toArray();
        $title = ['物业系统id','商户编号','合同号','店招','数采编号','登录账号','公司名称','合同面积','合同状态','签约位置名称','签约位置代码','业态','所属楼层',
            '期初余额','账户余额','发票类型','发票抬头','开户行账号','开户行名称','公司地址','税号','开票手机号','个人/公司','邮箱'];
        $export = [];
        foreach ($data as $k=>$v){
            $res = [];
            if($v['biz_state']=='canceled')$biz_state = '已作废';
            if($v['biz_state']=='effect')$biz_state = '已生效';
            if($v['biz_state']=='ineffect')$biz_state = '未生效';
            if($v['biz_state']=='stopped')$biz_state = '已停止';
            if($v['invoiceType']==1)$invoiceType = '普通发票';
            if($v['invoiceType']==2)$invoiceType = '专用发票';
            if($v['invoiceType']==0)$invoiceType = '暂未配置';
            $res['id'] = "\t".$v['id']."\t";
            $res['merchant_sn'] = "\t".$v['merchant_sn']."\t";
            $res['code'] = "\t".$v['code']."\t";
            $res['name'] = $v['name'];
            $res['UniqueKey'] ="\t". $v['UniqueKey']."\t";
            $res['mobile'] = $v['mobile'];
            $res['company'] = $v['company'];
            $res['rent_area'] = $v['rent_area'];
            $res['biz_state'] = $biz_state;
            $res['positions_name'] = $v['positions_name'];
            $res['positions_code'] = $v['positions_code'];
            $res['activities'] = $v['activities'];
            $res['lcName'] = $v['lcName'];
            $res['start_balance'] = $v['start_balance']/100;
            $res['balance'] = $v['balance']/100;
            $res['invoiceType'] = $invoiceType;
            if(!empty($v['merchantInvoice'])){
                if($v['merchantInvoice']['type']==0) $type = '公司';
                if($v['merchantInvoice']['type']==1) $type = '个人';
                $res['title'] = $v['merchantInvoice']['title'];
                $res['bankAccount'] = $v['merchantInvoice']['bankAccount'];
                $res['bankName'] = $v['merchantInvoice']['bankName'];
                $res['companyAddress'] = $v['merchantInvoice']['companyAddress'];
                $res['taxNumber'] = $v['merchantInvoice']['taxNumber'];
                $res['type'] = $type;
                $res['email'] = $v['merchantInvoice']['email'];
            }

            $export[] = $res;
        }

        return export_excel('商户信息_'.date('Y-m-d'),$title,$export);
    }

    /**
     * 获取商户水表信息
     */
    public function getMonthWater($param = [], $order = '', $where = [], $time){
        $where[] = ['r.status', '=', 0];
        $where[] = ['r.dataTime', '=', $param['month']];
        $where[] = ['r.merchant_id', '<>', 1918];
        $where[] = ['w.status', '=', 1];
        $where[] = ['w.type', 'in', [2,4]];
        if(!empty($param['merchant_id'])){
            $where[] = ['m.id','=',$param['merchant_id']];
            session('merchant_id_water',$param['merchant_id']);
        }else{
            Session::delete('merchant_id_water');
        }
        $data = Merchant::alias('m')
            ->join('tang_month_water_log r', 'r.merchant_id=m.id', 'LEFT')
            ->join('tang_watch_maintain w', "r.pointId = w.pointId", 'LEFT')
            ->where($where)
            ->field('m.id,m.merchant_sn,m.name,m.company,r.userId,r.pointId,r.dataTime,r.start,r.end,r.rate')
            ->order("m.id asc")
            ->page(PAGE)
            ->limit(LIMIT)->select()->toArray();
        foreach ($data as $key=>$val){
            $result = waterBill($val,$param['price']);
            $data[$key]['money'] = $result['allMoney'];
            $data[$key]['useWater'] = $result['water'];
        }
//        $newArray = [];
//        foreach ($data as $value) {
//            if (empty($newArray[$value['id']])) {
//                $newArray[$value['id']] = $value;
//            } else {
//                $newArray[$value['id']]['money'] =  bcadd($newArray[$value['id']]['money'], $value['money'], 2);
//                $newArray[$value['id']]['useWater'] =  bcadd($newArray[$value['id']]['useWater'], $value['useWater'], 2);
//            }
//        }
//        $newArray = array_values($newArray);
//        foreach ($newArray as $key=>$row){
//            $newArray[$key]['money'] = sprintf('%01.2f',$row['money']);
//            $newArray[$key]['useWater'] = sprintf('%01.2f',$row['useWater']);
//        }
//        $count = count($newArray);
        return parent::ajaxResult($data, count($data));

    }
    /**
     * @param $param 获取对应商户需要交纳的列表,小程序录入
     * @param $order
     * @param $where
     * @param $time
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getMonthRecord($param = [], $order = '', $where = [], $time)
    {
        if (isset($param["name"]) && !empty($param['name'])) {
            $where[] = ["m.name", "=", $param["name"]];
        }
        if(!empty($param['merchant_id'])){
            $where[] = ['m.id','=',$param['merchant_id']];
            session('merchant_id',$param['merchant_id']);
        }else{
            Session::delete('merchant_id');
        }
        $where[] =[ 'w.status','=',1];
        $where[] =['r.dataTime' ,'=', $time];
        $where[] =['r.status' ,'=', 0];
        $where[] =['r.merchant_id' ,'<>', 0];
        $where[] =['r.merchant_id' ,'<>',1918];
//        $where[] =['w.type' ,'=', 3];
        //此时不牵扯倍率的问题,不需查询
        $data = Merchant::alias('m')
            ->where($where)
            ->join('tang_month_sole_electricity_log r', 'm.id=r.merchant_id', 'LEFT')
            ->join('tang_watch_maintain w', "w.pointId = r.pointId", 'LEFT')
            ->field('m.id,m.merchant_sn,m.name,w.initial_degrees,r.merchant_id,r.userId,r.pointId,r.pointName,r.dataTime,
            r.rate,r.percent,r.totalMoney,m.company,r.totalPower,r.zongEnd,r.zongMoney,r.zongPower,r.zongStart')
            ->select()->toArray();
        foreach ($data as $key => $val) {
            $data[$key]['month'] = $time;
            $result = handWritten($val,$param['price']); //手抄表计算
            $data[$key]['electricity'] = sprintf('%01.2f',$result['allElectricity']);
            $data[$key]['money'] = sprintf('%01.2f',$result['allMoney']);
        }
//        $newArray = [];
//        foreach ($data as $value) {
//            if (empty($newArray[$value['id']])) {
//                $newArray[$value['id']] = $value;
//            } else {
//                $money = bcadd($newArray[$value['id']]['money'], $value['money'], 4);
//                $electricity = bcadd($newArray[$value['id']]['electricity'], $value['electricity'], 4);
//                $newArray[$value['id']]['money'] = $money;
//                $newArray[$value['id']]['electricity'] = $electricity;
//            }
//        }
//        $newArray = array_values($newArray);
//        foreach ($newArray as $key=>$row){
//            $newArray[$key]['money'] = sprintf('%01.2f',$row['money']);
//            $newArray[$key]['electricity'] = sprintf('%01.2f',$row['electricity']);
//        }
//        $count = count($newArray);
//        return parent::ajaxResult($newArray, $count);
        $count = count($data);
        return parent::ajaxResult($data, $count);

    }

    /**
     * @return 获取接口读取的商户峰谷平电量
     */
    public function getMonthDegree($param = [], $order = '', $where = [], $time)
    {
        $where[] = ['r.status', '=', 0];
        $where[] = ['r.dataTime', '=', $param['month']];
        $where[] = ['r.merchant_id', '<>', 0];
        $where[] = ['r.merchant_id', '<>', 1918];
        $where[] =['w.type','=',1];
        $where[] =[ 'w.status','=',1];
        if(!empty($param['merchant_id'])){
            $where[] = ['m.id','=',$param['merchant_id']];
            session('merchant_id',$param['merchant_id']);
        }else{
            Session::delete('merchant_id');
        }
        if(!empty($param['activities'])){
            $where[] = ['m.activities','=',$param['activities']];
        }
        if(!empty($param['lcName'])){
            $where[] = ['m.lcName','=',$param['lcName']];
        }
        $data = Merchant::alias('m')
            ->join('tang_month_electricity_degree r', 'm.id=r.merchant_id', 'LEFT')
            ->join('tang_watch_maintain w', "r.pointId = w.pointId", 'LEFT')
            ->where($where)
            ->field('m.id,m.merchant_sn,m.name,m.company,r.userId,r.pointId,r.pointName,r.dataTime,r.fengStart,r.fengEnd,r.guStart,r.guEnd,r.pingStart,r.pingEnd,r.rate')
            ->order("m.id asc")
            ->page(PAGE)
            ->limit(LIMIT)->select()->toArray();
        foreach ($data as $key => $val) {
            $data[$key]['month'] = $time;
            $res = rate($val,$param);
            $data[$key]['fMoney'] = $res['fMoney'];
            $data[$key]['gMoney'] =  $res['gMoney'];
            $data[$key]['pMoney'] =  $res['pMoney'];
//            $data[$key]['pointId'] =  $val['pointId'];
            $data[$key]['electricity'] =sprintf('%01.2f',$res['allElectricity']);
            $data[$key]['money'] = sprintf('%01.2f',$res['allMoney']);
//            $data[$key]['electricity'] = $res['allElectricity'];
//            $data[$key]['money'] = $res['allMoney'];
        }
//        $newArray = [];
//        foreach ($data as $value) {
//            if (empty($newArray[$value['id']])) {
//                $newArray[$value['id']] = $value;
//            } else {
//                $money = bcadd($newArray[$value['id']]['money'], $value['money'], 6);
//                $electricity = bcadd($newArray[$value['id']]['electricity'], $value['electricity'], 6);
//                $newArray[$value['id']]['money'] = $money;
//                $newArray[$value['id']]['electricity'] =$electricity;
//            }
//        }
//        $newArray = array_values($newArray);
//        foreach ($newArray as $key=>$row){
//            if($row['name']=='-'||empty($row['name'])){
//                $newArray[$key]['name'] = $row['company'];
//            }
//            $newArray[$key]['money'] = sprintf('%01.2f',$row['money']);
//            $newArray[$key]['electricity'] = sprintf('%01.2f',$row['electricity']);
//        }
        $count = count($data);
        return parent::ajaxResult($data, $count);
    }
    public function getBizStateAttr($time)
    {
        return $time; // TODO: Change the autogenerated stub
    }

    public function record()
    {
        return $this->hasMany(MonthElectricityRecord::class, 'merchant_id', 'id')->whereTime('create_time', 'last month')->where('status',0)->field('last_electricity,merchant_id,now_electricity');
    }

    /**  表号维护表
     * @return \think\model\relation\HasMany
     */
    public function WatchMainTain()
    {
        return $this->hasMany(WatchMaintain::class, 'merchant_id', 'id')->where('status', 1);
    }

    public function MerchantMobile()
    {
        return $this->hasMany(MerchantMobile::class, 'merchant_id', 'id')->field('mobile');
    }
    /**
     * 组织表
     */
    public function organization(){
        return $this->hasOne(OrganizationConfig::class,'id','organization')->field('id,name');
    }
    /**
     *二级组织
     */
    public function organizationOne(){
        return $this->hasOne(OrganizationConfig::class,'id','organization_one')->field('id,name');
    }
    /**
     * 发票信息
     */
    public function merchantInvoice(){
        return $this->hasOne(MerchantInvoice::class,'merchant_id','id');
    }
}